<template>
  <div class="async-config-modal">
    <je-modal
      v-model:visible="isShow"
      title="字段配置同步"
      :resize="false"
      width="960px"
      :maximizable="false"
      cancel-button
      :ok-button="okButton"
    >
      <div class="async-config-content">
        <div class="dircible">
          通过其他功能字段同步完成本功能字段列表、表单的配置信息。
          <div style="color: #3265f5"
            >字段配置同步策略说明，【全部字段】：所选功能的全部字段编码对比本功能字段，同步本表相同字段的配置信息；【指定字段】：所选功能的指定字段对比本功能字段，同步本表相同字段的配置信息；【排除字段】：所选功能去掉排除字段的剩余字段对比本功能字段，同步本表相同字段的配置信息。</div
          >
        </div>
        <je-form
          ref="formRef"
          class="form"
          :rules="rules"
          :model="formState"
          :colon="false"
          autocomplete="off"
        >
          <je-row>
            <je-col :span="5">
              <je-form-item label="功能" name="funcName">
                <je-grid-select
                  v-model:value="formState.funcName"
                  name="funcName"
                  config-info="JE_CORE_FUNCINFO,funcName~funcCode,FUNCINFO_FUNCNAME~FUNCINFO_FUNCCODE,S"
                  :orders="[{ code: 'SY_CREATETIME', type: 'DESC' }]"
                  :querys="queryArr"
                  @select="selectFunc"
                />
              </je-form-item>
            </je-col>
            <je-col :span="7" :offset="1">
              <je-form-item label="功能编码" name="funcCode">
                <je-input v-model:value="formState.funcCode" name="funcCode" disabled />
              </je-form-item>
            </je-col>
            <je-col :span="6" :offset="1">
              <je-form-item label="策略">
                <je-select v-model:value="formState.quickQueryType" allow-clear>
                  <je-select-option
                    v-for="(item, index) in [
                      { code: '1', text: '全部字段' },
                      { code: '2', text: '部分字段' },
                      { code: '3', text: '排除字段' },
                    ]"
                    :key="index"
                    :value="item.code"
                  >
                    {{ item.text }}
                  </je-select-option>
                </je-select>
              </je-form-item>
            </je-col>
            <je-col v-if="formState.quickQueryType != '1'" :offset="1"
              ><div class="selectField" @click="clickSelectField">选择字段</div></je-col
            >
          </je-row>
        </je-form>
        <div class="async-config-table">
          <je-table
            ref="asyncConfigRef"
            resizable
            border
            height="100%"
            show-overflow
            header-align="center"
            :auto-resize="true"
            row-id="id"
            row-key
            align="center"
            :data="testData"
            size="mini"
          >
            <je-table-column title="No." type="seq" width="100" />
            <je-table-column title="字段名称" width="220" field="RESOURCECOLUMN_NAME" />
            <je-table-column title="字段编码" field="RESOURCECOLUMN_CODE" align="center" />
            <je-table-column title="类型" width="180" align="center">
              <template #default="{ row }">{{
                getSelectCodeToLabel('JE_FUNC_COLUMN_XTYPE', row.RESOURCECOLUMN_XTYPE)
              }}</template>
            </je-table-column>
            <je-table-column width="60" title="操作">
              <template #default="{ row }">
                <i
                  style="font-size: 16px; cursor: pointer"
                  class="fal fa-times"
                  @click="deleteColumnTable(row)"
                ></i>
              </template>
            </je-table-column>
          </je-table>
        </div>
      </div>
    </je-modal>
  </div>
</template>

<script>
  import { ref, defineComponent, reactive, toRefs, watch, onBeforeMount } from 'vue';
  import { Modal, Input, Select, Form, Grid, InputSelect, Row, Col } from '@jecloud/ui';
  import { SelectWindow } from '@jecloud/func';
  import { UpdateFunctionAsyncConfig } from '@/api/index';
  import { getDDItemInfo, isNotEmpty, loadDDItemByCodes } from '@jecloud/utils';
  export default defineComponent({
    name: 'TipViewPanel',
    components: {
      JeModal: Modal,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      JeRow: Row,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeCol: Col,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JeGridSelect: InputSelect.Grid,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
      record: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    emits: ['changeTipShow'],
    setup(props) {
      const isShow = ref(props.visble);
      const state = reactive({
        visible: props.visble,
        formRef: ref(),
        formState: {
          quickQueryType: '1',
        },
        rules: {},
        testData: [],
        asyncConfigRef: '',
        JE_CORE_FUNCINFO_ID: '', // 功能ID
      });
      watch(
        () => state.formState.quickQueryType,
        (val) => {
          if (val == '1') {
            state.testData = [];
          }
        },
      );
      const methods = {
        selectFunc({ rows }) {
          if (!rows.length) {
            return false;
          }
          const { FUNCINFO_FUNCCODE, JE_CORE_FUNCINFO_ID } = rows[0];
          console.log('rows', rows);
          state.formState.funcCode = FUNCINFO_FUNCCODE;
          // 功能ID
          state.formState.JE_CORE_FUNCINFO_ID = JE_CORE_FUNCINFO_ID;
        },
        // 删除操作
        deleteColumnTable(row) {
          const $table = state.asyncConfigRef.$plugin;
          $table.remove(row);
        },
        // 点击确定
        okButton() {
          if (!state.formState.funcCode) {
            Modal.alert('请先选择功能！', 'info');
            return false;
          }
          const data = state.asyncConfigRef.$plugin.getTableData().tableData || [];
          if (state.formState.quickQueryType != '1' && !data.length) {
            Modal.alert('请选择字段数据！', 'info');
            return false;
          }
          // 将data 获取所有的code
          console.log('data', data);
          const dataCodeArr = [];
          data.map((item) => {
            dataCodeArr.push(item.RESOURCECOLUMN_CODE);
          });
          const params = {
            toFuncCode: props.record.FUNCINFO_FUNCCODE,
            formFuncCode: state.formState.funcCode,
            columnCodes: (dataCodeArr && dataCodeArr.length && dataCodeArr.join(',')) || '',
            type: state.formState.quickQueryType,
          };
          UpdateFunctionAsyncConfig(params)
            .then((res) => {
              Modal.message(res.message, 'success');
            })
            .catch((err) => {
              Modal.alert(err.message, 'error');
            });
        },
        getSelectLabel(value, list, valueProp = 'value', labelField = 'label') {
          const item = list.find((item) => item[valueProp] === value);
          return item ? item[labelField] : null;
        },
        getSelectCodeToLabel(dictionary, code) {
          const item = getDDItemInfo(dictionary, code);

          if (isNotEmpty(item)) {
            return item.text;
          }
          return '';
        },
        // 点击选择字段
        clickSelectField() {
          if (!state.formState.funcCode) {
            Modal.alert('请先选择功能！', 'info');
            return false;
          }
          if (state.formState.quickQueryType == '1') {
            return false;
          }
          SelectWindow.show({
            title: '选择字段',
            type: 'grid',
            orders: [
              // { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ],
            querys: [
              {
                code: 'RESOURCECOLUMN_FUNCINFO_ID',
                value: state.formState.JE_CORE_FUNCINFO_ID,
                type: '=',
                cn: 'and',
              },
              // { code: 'TABLECOLUMN_ISCREATE', type: '=', value: '1', cn: 'and' },
            ],
            configInfo: 'JE_CORE_RESOURCECOLUMN,,,M',
            callback: function ({ rows }) {
              state.testData = rows || [];
              // (rows || []).map((item) => state.testData.push(item));
            },
          });
        },
      };
      onBeforeMount(() => {
        // 获取字典数据
        loadDDItemByCodes(['JE_FUNC_COLUMN_XTYPE']);
      });
      return {
        isShow,
        ...methods,
        ...toRefs(state),
        queryArr: ref([
          {
            code: 'FUNCINFO_FUNCCODE',
            type: '!=',
            value: props.record.FUNCINFO_FUNCCODE,
            cn: 'and',
          },
          {
            code: 'FUNCINFO_FUNCTYPE',
            type: 'in',
            value: ['TREE', 'FUNC', 'VIEW'],
            cn: 'and',
          },
        ]),
      };
    },
  });
</script>
<style lang="less" scoped>
  .async-config-modal {
    .async-config-content {
      height: 100%;
      position: relative;
      .async-config-table {
        position: absolute;
        bottom: 0;
        top: 180px;
        width: 100%;
        overflow: scroll;
      }
      .dircible {
        background: #f9f9f9;
        padding: 14px 26px;
        line-height: 20px;
        margin-bottom: 20px;
      }
      .selectField {
        line-height: 32px;
        background: #edf0f1;
        color: #777;
        border: 1px solid #edf0f1;
        padding: 0 12px;
        cursor: pointer;
        // margin-left: 100px;
      }
      .inputWrap {
        position: relative;
        .setIcon {
          position: absolute;
          top: 50%;
          right: 10px;
          transform: translate(0, -50%);
          cursor: pointer;
          z-index: 1000;
        }
      }
    }
  }
</style>
